#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 14:57
# @Author : 吴敬超
# explain:


# from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
from netCDF4 import date2index
from netCDF4 import num2date, date2num
from datetime import datetime
from matplotlib import dates

import csv
import glob
import  sys

plt.rcParams['font.sans-serif'] = ['SimHei']        # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False            # 用来正常显示负号

def to_csv(source_file):
    # 读取nc数据
    dataset = Dataset(source_file)
    print(dataset.variables.keys())

    # 获取相应数组集合--纬度经度温度深度
    # Dimension
    time = nc_obj.variables['time'][:]
    lev = nc_obj.variables['depth'][:]
    lat = nc_obj.variables['latitude'][:]
    lon = nc_obj.variables['longitude'][:]

    # Variables
    vo = nc_obj.variables['vo'][:]
    uo = nc_obj.variables['uo'][:]
    print('-------------------------------------------------------------------')
    # 文件名不含扩展名
    source_file = source_file.split('.')
    file_name = source_file[0]
    print(lev)

    # 创建csv目标文件
    try:
        # 打开目标csv文件
        with open("New_"+file_name+'.csv', 'a', newline='') as targetFile:
            # 创建写入流
            writer = csv.writer(targetFile)
            # 写入表头
            writer.writerow(('time', 'lat', 'lon', '{}m'.format(lev), 'vo', 'uo'))
            # 写入数据
            for i in range(len(time)):
                for j in range(len(lev)):
                    for k in range(len(lat)):           # k为纬度
                        for l in range(len(lon)):       # l为经度
                                if  str(vo[i][j][k][l]) not in '--':
                                     writer.writerow((str(num2date(tim[i], units=tim.units, calendar=tim.calendar))[0:20], lev[j], lat[k], lon[l], vo[i][j][k][l], uo[i][j][k][l]))#dates.num2date(time[i], tz=None)

        targetFile.close()              # 关闭文件
        print('Get'+file_name+'.csv Success!')
    except Exception as e:              # 抛异常
        print('Error :'+str(e))


if '__name__ ==__main__':
    print("start transformation...")
    to_csv('global-analysis-forecast-phy-001-024_1571504740261.nc')
    print('Transformed successfully')